"""
小小词典 V1.0 
Copyright (C) 2025  Yang xiaofan 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""
import sqlite3
import requests
from bs4 import BeautifulSoup
 
def init_db():
    conn = sqlite3.connect('translations.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS translations
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  english TEXT UNIQUE NOT NULL,
                  chinese TEXT NOT NULL,
                  pos TEXT,
                  create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
    # 新增生词本表
    c.execute('''CREATE TABLE IF NOT EXISTS vocabulary_book
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  word_id INTEGER UNIQUE,
                  add_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                  FOREIGN KEY(word_id) REFERENCES translations(id))''')
    conn.commit()
    conn.close()
    
def add_to_vocabulary(word):
    conn = sqlite3.connect('translations.db')
    c = conn.cursor()
    # 获取单词ID
    c.execute("SELECT id FROM translations WHERE english=?", (word,))
    word_id = c.fetchone()
    if word_id:
        try:
            c.execute("INSERT OR IGNORE INTO vocabulary_book (word_id) VALUES (?)", 
                     (word_id[0],))
            conn.commit()
            print(f"【{word}】已成功加入生词本")
        except sqlite3.IntegrityError:
            print(f"【{word}】已在生词本中")
    else:
        print("请先查询该单词确保其存在于数据库")
    conn.close()
 
def show_vocabulary():
    conn = sqlite3.connect('translations.db')
    c = conn.cursor()
    c.execute('''SELECT t.english, t.chinese, t.pos 
                 FROM translations t JOIN vocabulary_book v ON t.id = v.word_id
                 ORDER BY v.add_time DESC''')
    print("\n=== 我的生词本 ===")
    for idx, (en, cn, pos) in enumerate(c.fetchall(), 1):
        print(f"{idx}. {en} ({pos}): {cn}")
    conn.close()
    
def save_to_db(english, chinese, pos):
    conn = sqlite3.connect('translations.db')
    c = conn.cursor()
    c.execute("INSERT OR IGNORE INTO translations (english, chinese, pos) VALUES (?, ?, ?)",
              (english, chinese, pos))
    conn.commit()
    conn.close()
    
def check_in_db(word):
    conn = sqlite3.connect('translations.db')
    c = conn.cursor()
    c.execute("SELECT english, chinese, pos FROM translations WHERE english=?", (word,))
    result = c.fetchone()
    conn.close()
    return result if result else None
    
def translate_with_pos(word):
    # 先查本地数据库
    db_result = check_in_db(word)
    if db_result:
        print(f"该单词已在本地数据库查找到，翻译解释如下：")
        print(f"{db_result[0]} ({db_result[2]}): {db_result[1]}")
        choice = input("继续网络查询请输入w，直接退出请按回车：").strip().lower()
        if choice != 'w':
            return None
    url = f"https://dict.youdao.com/w/eng/{word}/"
    headers = {'User-Agent': 'Mozilla/5.0'}
    
    try:
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 获取中文释义
        trans = soup.find('div', class_='trans-container').get_text(strip=True)
        
        # 获取词性标注
        pos_tag = soup.find('span', class_='pos')
        pos = pos_tag.get_text() if pos_tag else "无词性标注"
        save_to_db(word, trans, pos)
        return f"{word} ({pos}): {trans}"
    except Exception as e:
        return f"翻译失败: {str(e)}"
 
if __name__ == "__main__":
    init_db()
    print("命令： \q 退出；\w 加入生词本 \s 查看生词本 \h 查看帮助")
    while True:
        query = input("请输入英文单词或命令(输入\q退出): ").strip()
        if query.lower() == '\q':
            break
        if query.lower() == '\w':
            word = input("输入要收藏的单词: ").strip()
            add_to_vocabulary(word)
            continue
        if query.lower() == '\s':
            show_vocabulary()
            continue
        if query.lower() == '\h':
            print("命令： \q 退出；\w 加入生词本 \s 查看生词本 \h 查看帮助")
            continue
        trans = translate_with_pos(query)
        if trans:
            print(f"-    {trans}")